/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package commons;


import java.io.BufferedOutputStream;
import java.text.DateFormat;
import java.io.*;
import java.text.SimpleDateFormat;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 *
 * @author TonyLogic
 */
public class DataProcessing{
	
		
    public static void makeDirAndMoveFile(File searchDir)
    {
        
        String writeDir = "F:/Switchbox/Equivital_core_patches/";
        
        List<File> Files = new ArrayList<File>();
        
        for(int z=002; z<145; z++)
        {      	
            if(z<10)
            {
              	 File dir =new File(writeDir+"00"+z);       	 
        	 System.out.println(dir.mkdir());

            }else if (z>=10 && z< 100)
            {
        	File dir =new File(writeDir+"0"+z);
       		System.out.println( dir.mkdir());
            }
            else if (z >= 100)
            {
            (   new File(writeDir+z)).mkdir();
            System.out.println( writeDir+z);
            }        	
        }
            
        // Move Files equivital files
        for( int z=002; z<145; z++ )
       {
  	
            String PatientNumber = "0";   	
            if(z<10)
            {
        
                PatientNumber="00"+z;
           }else if (z>=10 && z< 100)
            {
                PatientNumber="0"+z;
            }
            else if (z >= 100)
            {
                PatientNumber=Integer.toString(z);
            }
        	
          System.out.println(PatientNumber);        
          IOhandler.searchForDatFiles(searchDir,Files,PatientNumber,false,false);
        	
     
        
       for (int i=0;i<Files.size();i++)
        {
          
    	   String pathPatientNumber = Character.toString( Files.get(i).getPath().charAt(28))+
    			   Character.toString( Files.get(i).getPath().charAt(29))+
    			   Character.toString( Files.get(i).getPath().charAt(30));	        	
       	if(Files.get(i).getPath().contains("Core_Patch") && pathPatientNumber.contentEquals(PatientNumber) )
       	{
       		   File CorePatch  = Files.get(i); 
       	           String path = CorePatch.getPath();
        		      		
                System.out.println(path);
        	System.out.println(path.substring(path.length()-23, path.length()));
        		
  		String dir = "F:/Switchbox/Equivital_core_patches/"+PatientNumber+"/"+path.substring(path.length()-23, path.length());
  		DataProcessing.moveFile(path, dir);
   		
       	}
          if( Files.get(i).getPath().contains("Accelerometer") && Files.get(i).getName().endsWith(".csv"))
           {                
                 DataProcessing.AggraTimeSeries(Files.get(i), 300);
               return;
            }
       }
        
       Files.clear();
       
      }
        
        
    }
	
    
    public static void moveFile(String aFile, String dir)
   { 
		
		
		BufferedReader br = null;
		BufferedOutputStream io= null;
		
		String output =" ";
        try{
    	
	           
        br = new BufferedReader(new FileReader(aFile));
    	 io = new BufferedOutputStream(new FileOutputStream(dir));


		
   		
         for(String readLine; (readLine = br.readLine()) !=null;)
         {
			 	
        	  readLine = readLine+"\n"; 
                  byte bites[] = readLine.getBytes();
                  io.write(bites);		 
         }
		
		br.close();
                io.close();
		
		}  catch (Exception e){
         
            System.out.println(e.getMessage());
         }
	
  }
    
  public static boolean checkTimeDiff(Date aStartDate, Date aEndDate, int TimeLimit)
  {
	  
	  long difference = aEndDate.getTime() - aStartDate.getTime();
	  
	  if(difference/1000 >=TimeLimit){
		  return true;
	  }
	  else{
		  return false;
	  }
	  
  }
    
    
    public static void AggraTimeSeries(File aFile, int TimeLimit)
    {
       System.out.println("Deze heb ik gekregen"+aFile.getPath());
       ArrayList AggraValues = new ArrayList<String[]>();
       BufferedOutputStream io = null;
       BufferedReader br = null;
       
       DecimalFormat df = new DecimalFormat("0.00");
       DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
       Date dateBegin = null;
                   
       boolean foundData = false;
       
       try{
           
         br = new BufferedReader(new FileReader(aFile.getPath()));                 
         io = new BufferedOutputStream(new FileOutputStream(aFile.getPath()+"_comp.csv"));
         
         
                              
         for(String readLine; (readLine = br.readLine()) !=null;)
         {
           
            
          if ( foundData == true )   
          {
                                            
            if(AggraValues.isEmpty() == false )
            {
            	AggraValues.add(readLine.split(",")); 
            	
                String splitedValues[] = readLine.split(",");                                                                                            
                Date dateEnd = formatter.parse(splitedValues[0]);
                           
                                       
                if(checkTimeDiff(dateBegin,dateEnd,TimeLimit) ){
                                     
                    String[] firstValue = (String[]) AggraValues.get(0);
                                   
                    for(int z=1; z<AggraValues.size(); z++)
                    {
                        String[] currentValue =  (String[]) AggraValues.get(z);
                      
                       for(int y=1; y<firstValue.length;y++) 
                       {                            
                           double aggraVal = Double.parseDouble(firstValue[y])+Double.parseDouble(currentValue[y]);
                           firstValue[y] = Double.toString(aggraVal) ;                         
                       }
                      
                    }
                     
                                     
                    String writeToFile = splitedValues[0]+",";
                    int divide =AggraValues.size();
                    System.out.println(divide);
                    
                    for(int y=1; y<firstValue.length;y++) 
                       {
                           double AggraValue =Double.parseDouble(df.format( Double.parseDouble( firstValue[y])/divide).replace(",", "."));                            
                           writeToFile=writeToFile+AggraValue+",";                          
                       }
                    writeToFile = writeToFile+"\n";
                    
                    //System.out.println("Dit gaat hij schrijven= \n"+writeToFile);
                    byte bites[] = writeToFile.getBytes();                 
                    io.write(bites);
                    AggraValues.clear();
     
                }
                else{
                    
                    AggraValues.add(readLine.split(","));  
                }
            }
            else{ 
                String inputValues[] = readLine.split(",");
                dateBegin = formatter.parse(inputValues[0]);
                AggraValues.add(inputValues);   
            }
          }
           else  if(foundData == false)
             {
                 foundData = readLine.matches("[0-9[,][-][:][.] ]+") ;
             }
         
       
               
         }
         
           io.close();
           br.close();
           
              
        }
        catch (Exception e){
            System.out.append("wtf");
            System.out.println(e.getMessage());
         }
      
       
        
              
    }
    
    
            
   public static void CleanEquivital( List<File> aPatientEqvuivitalFiles, File aPillTimeSchema,int TimeLimit, String aPatientNumber )
   {
	   
	  
       ArrayList AggraValues = new ArrayList<String[]>();
       ArrayList StringsToWrite = new ArrayList<String>();
       boolean first5HoursCheck = false;
           
       DecimalFormat df = new DecimalFormat("0.00");
       DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
       Date dateBegin = null;
       Date dateEnd = null;
   	    			 	   
     
       String patientNumbers = "";
       
       BufferedOutputStream io = null;
       BufferedReader br = null;
       
           
       try
       {    		        	
           	for(int i=0;i<aPatientEqvuivitalFiles.size();i++)
           	{
    		  	   
           		br = new BufferedReader(new FileReader(aPatientEqvuivitalFiles.get(i)));
           		System.out.println("Hier gaat het om:"+aPatientEqvuivitalFiles.get(i) );
       	
            	
           		//First row is only values.
           		String readLine = br.readLine();
           		readLine = br.readLine();
       	
           		String splitedValues[] = readLine.split(",");                                                                                            
           		dateBegin = formatter.parse(splitedValues[0]);
       	     	
           		// First a 5 hour time removal.
           		while( (readLine = br.readLine()) !=null)
           		{
           			splitedValues = readLine.split(",");                                                                                            
           			dateEnd =  formatter.parse(splitedValues[0]);
            
           			if(first5HoursCheck == false){     		
           				if(checkTimeDiff(dateBegin,dateEnd,18000)){
           					System.out.println(dateEnd.toString());
           					first5HoursCheck = true;    
           					
           				}      		
           			}           			 
           			else{   
           				
           			
           				if(AggraValues.isEmpty() ){
           					if(checkTem(splitedValues)){
               				checkWithPillSchema(splitedValues,aPillTimeSchema,aPatientNumber);              				
               				AggraValues.add(splitedValues);
               				dateBegin = formatter.parse(splitedValues[0]);
           					}
               			}
           				else if(!checkTimeDiff(dateBegin,dateEnd,TimeLimit)){
           					if(checkTem(splitedValues)){
           					checkWithPillSchema(splitedValues,aPillTimeSchema,aPatientNumber);
           					AggraValues.add(splitedValues);
           					}
        			
           				}
           				else{
           					//System.out.println(dateBegin);
           					//System.out.println(dateEnd);
           					AggraValues.clear();
           				}     		     		
           			}
      	
           		}
       	
           		
           	first5HoursCheck = false;		
           	}	      		      	                  	      
       }
       catch (Exception e)
       {
           System.out.println(e.getMessage());
       }
    	
    	
    }
   
   
   public static boolean checkTem(String[] splitedValues)
   {
	   if(Double.parseDouble(splitedValues[2]) < 35 || Double.parseDouble(splitedValues[2]) > 41 ){
		   System.out.println("Dit was de temp:"+splitedValues[2]);
		   return false;
	   }
	   else{
		   return true;
	   }
   }
   
   
   
   
   public static String[] checkWithPillSchema(String[] splitedValues,File aPillTimeSchema, String aPatientNumber){
	   
	   File inputWorkbook = aPillTimeSchema;        
       Workbook w;
       
	   try
       {
		    w = Workbook.getWorkbook(inputWorkbook);     
          	Sheet sheet = w.getSheet(0);
          	        
          	for(int i = 3; i<sheet.getRows();i++){
          	
          	Cell cell = sheet.getCell(0, i);
          		        	
         	if(Integer.parseInt(aPatientNumber) == Integer.parseInt(cell.getContents()) )
          	{
         		String Pill1 = sheet.getCell(1, i).getContents();
         		String Pill2 = sheet.getCell(2, i).getContents();
         		String Pill3 = sheet.getCell(3, i).getContents();
         		
         		if(Pill1.contentEquals(splitedValues[3]) || Pill2.contentEquals(splitedValues[3]) || Pill3.contentEquals(splitedValues[3]))
         		{
         			return splitedValues;
         		}
         		else
         		{
         			System.out.println(sheet.getCell(7, i).getContents());
         			System.out.println(splitedValues[0]+"  "+splitedValues[1]+" "+splitedValues[2]+"  "+splitedValues[3]);
         		}
         		
         		
          	}
         	
         	
          	}
       }
	   catch (Exception e)
       {
		   
           System.out.println("Error:"+e.getMessage());
       }
	   
	   
	   
	   
	   return splitedValues;
	   
	   
	   
   }
    
}


